package com.jyy.prefabricated.service;

import com.alibaba.fastjson.JSON;
import com.jyy.prefabricated.dto.AnswerDto;
import com.jyy.prefabricated.entity.Exam;
import com.jyy.prefabricated.entity.Question;
import com.jyy.prefabricated.entity.StudentExamQuestion;
import com.jyy.prefabricated.enums.QuestionTypeEnum;
import com.jyy.prefabricated.exception.CustomException;
import com.jyy.prefabricated.mapper.*;
import com.jyy.prefabricated.vo.StudentExamAreaVo;
import com.jyy.prefabricated.vo.StudentExamPaperVo;
import com.jyy.prefabricated.vo.StudentExamQuestionVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @version 1.0.0
 * @author: zjj
 */
@Transactional
@Service
public class StudentExamQuestionService {

    @Resource
    private StudentExamQuestionMapper studentExamQuestionMapper;

    @Resource
    private StudentExamMapper studentExamMapper;

    @Resource
    private ExamPaperAreaMapper examPaperAreaMapper;

    @Resource
    private ExamMapper examMapper;

    @Resource
    private QuestionOptionSortConfigMapper sortConfigMapper;

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionMapper questionMapper;


    /**
     * 新增
     *
     * @param studentExamQuestion
     * @return
     */
    public Integer insert(StudentExamQuestion studentExamQuestion) {
        studentExamQuestionMapper.insert(studentExamQuestion);
        return studentExamQuestion.getId();
    }

    /**
     * 更新
     *
     * @param studentExamQuestion
     * @return
     */
    public int update(StudentExamQuestion studentExamQuestion) {
        if (studentExamQuestion.getId() == null) {
            throw new CustomException("参数id不能为空");
        }
        return studentExamQuestionMapper.updateByPrimaryKeySelective(studentExamQuestion);
    }

    /**
     * 回答答案
     *
     * @param dto
     * @return
     */
    public StudentExamPaperVo answer(AnswerDto dto) {
        StudentExamQuestion studentExamQuestion = studentExamQuestionMapper.selectByPrimaryKey(dto.getId());
//        if(StringUtils.isNotBlank(dto.getAnswer()) && StringUtils.isBlank(studentExamQuestion.getAnswer())){
        studentExamQuestion.setAnswer(dto.getAnswer());
        studentExamQuestion.setSubjectiveAnswer(dto.getSubjectiveAnswer());
//            List<Option> options = optionMapper.selectByQuestionId(studentExamQuestion.getQuestionId());
//            //筛选出正确答案的选项数组
//            List<Integer> ids = options.stream().filter(e->e.getIfAnswer()).map(e->e.getId()).collect(Collectors.toList());
//            List<Integer> submitAnswers = JSON.parseArray(dto.getAnswer(),Integer.class);
//            Boolean ifRight = true;
//            for(Integer optionId : ids){
//                if(!submitAnswers.contains(optionId)){
//                    ifRight = false;
//                }
//            }
//            studentExamQuestion.setIfRight(ifRight);
        update(studentExamQuestion);
//        }
        return fetchQuestionsByStudentExamIdNo(studentExamQuestion.getStudentExamId());
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public int delete(Integer id) {
        return studentExamQuestionMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    public StudentExamQuestion selectById(Integer id) {
        return studentExamQuestionMapper.selectByPrimaryKey(id);
    }

    /**
     * 根据学员考试id获取学员考试试卷
     *
     * @param studentExamId
     * @return
     */
    public StudentExamPaperVo fetchQuestionsByStudentExamId(Integer studentExamId) {
        Exam exam = examMapper.selectByStudentExamId(studentExamId);

        StudentExamPaperVo paperVo = studentExamMapper.selectByStudentExamId(studentExamId);

        List<StudentExamAreaVo> areas = examPaperAreaMapper.selectByStudentExamId(studentExamId);

        //其他题
        List<StudentExamQuestionVo> questions = studentExamQuestionMapper.selectQuestionVoByStudentExamIdA(studentExamId);

        //材料题子题母题集合
        List<StudentExamQuestionVo> materialQuestionList = studentExamQuestionMapper.selectQuestionVoByStudentExamIdB(studentExamId);

        if (materialQuestionList != null && materialQuestionList.size() > 0) {
            for (StudentExamQuestionVo sev : materialQuestionList) {

                List<StudentExamQuestionVo> questionsSon = studentExamQuestionMapper.selectQuestionVoByStudentExamIdC(studentExamId, sev.getMaterialQuestionId());

                Question que = questionMapper.selectByPrimaryKey(sev.getMaterialQuestionId());
                //子题合成母题
                StudentExamQuestionVo tv = new StudentExamQuestionVo();
                tv.setQuestionType(que.getQuestionType());
                tv.setTitle(que.getName());
                tv.setAreaId(questionsSon.get(0).getAreaId());
                tv.setSort(questionsSon.get(0).getSort());
                tv.setContent(que.getContent());
                tv.setStudentExamQuestionVo(questionsSon);
                tv.setId(que.getId());
                tv.setScore(questionsSon.get(0).getScore());
                questions.add(tv);
            }

        }

//        for (StudentExamQuestionVo question : questions) {
//            Question result = questionService.selectById(question.getQuestionId());
//            //如果是材料题
//            if (result.getQuestionType().equals(QuestionTypeEnum.MATERIALS.getValue())) {
//
//                //材料题
//                Question details = questionService.selectById(question.getQuestionId());
//                question.setTitle(details.getMaterial());
//                //题目id
//                question.setQuestionId(details.getId());
//                //题干内容
//                question.setContent(details.getContent());
//                //材料题子题
//                if (question.getMaterialQuestionId() == null) {
//
//                    List<StudentExamQuestion> mlist = studentExamQuestionMapper.selectByMaterialQuestionId(details.getId());
//
//                    List<StudentExamQuestionVo> seqlist = new ArrayList<>();
//                    for (StudentExamQuestion s : mlist) {
//                        Question d = questionService.selectById(s.getQuestionId());
//                        StudentExamQuestionVo seqv = new StudentExamQuestionVo();
//
//                        //题目id
//                        seqv.setQuestionId(d.getId());
//                        //题目内容
//                        seqv.setTitle(d.getName());
//                        //参考问答答案
//                        seqv.setAnswer(d.getQuestionAnswer());
//                        //学生答案（问答题、填空题）
//                        seqv.setSubjectiveAnswer(s.getSubjectiveAnswer());
//                        //学生答案（单选、多选、判断）
//                        seqv.setAnswer(s.getAnswer());
//                        //题目类型
//                        seqv.setQuestionType(d.getQuestionType());
//                        //题目顺序
//                        seqv.setSort(s.getSort());
//                        //答案解析
//                        seqv.setAnswerKey(d.getAnswerKey());
//                        //参考判断题答案
//                        seqv.setJudgmentAnswer(d.getJudgmentAnswer());
//                        seqlist.add(seqv);
//
//                    }
//                    question.setStudentExamQuestionVo(seqlist);
//                }
//            }
//        }

//        if(exam.getIfRandom()){
//            //随机出题选项也需要打乱顺序,先查询是否生成题目选项顺序
//            List<QuestionOptionSortConfig> configs = sortConfigMapper.selectByStudentExamId(studentExamId);
//            if(configs.size() > 0){
//                //说明之前已经生成了排序了,按照保存的配置进行排序
//                for(StudentExamQuestionVo question : questions){
//                    QuestionOptionSortConfig config = configs.stream().filter(e->e.getExamQuestionId().equals(question.getId())).findAny().get();
//                    List<ExamQuestionOptionVo> options = new ArrayList<>();
//                    List<Integer> idSortConfig = JSON.parseArray(config.getConfig(), Integer.class);
//                    for(Integer optionId : idSortConfig){
//                        options.add(question.getOptions().stream().filter(e->e.getId().equals(optionId)).findAny().get());
//                    }
//                    question.setOptions(options);
//                }
//            } else {
//                //说明还没有生成选项排序
//                List<QuestionOptionSortConfig> configList = new ArrayList<>();
//                for(StudentExamQuestionVo question : questions){
//                    List<ExamQuestionOptionVo> options = question.getOptions();
//                    Collections.shuffle(options);
//                    question.setOptions(options);
//                    List<Integer> idSortConfig = options.stream().map(e->e.getId()).collect(Collectors.toList());
//                    String configJson = JSON.toJSONString(idSortConfig);
//                    QuestionOptionSortConfig config = new QuestionOptionSortConfig();
//                    config.setStudentExamId(studentExamId);
//                    config.setExamQuestionId(question.getId());
//                    config.setConfig(configJson);
//                    configList.add(config);
//                }
//                if(configList.size() > 0){
//                    sortConfigMapper.batchInsert(configList);
//                }
//            }
//        }
        if (questions != null && questions.size() > 0) {
            paperVo.setQuestionCount(questions.size());
            for (StudentExamAreaVo area : areas) {
                area.setQuestions(questions.stream().filter(e -> e.getAreaId().equals(area.getAreaId())).collect(Collectors.toList()));
            }
        }
        paperVo.setAreas(areas);
        return paperVo;
    }


    /**
     * 根据学员考试id获取学员考试试卷(没有答案和解析)
     *
     * @param studentExamId
     * @return
     */
    public StudentExamPaperVo fetchQuestionsByStudentExamIdNo(Integer studentExamId) {
        Exam exam = examMapper.selectByStudentExamId(studentExamId);

        StudentExamPaperVo paperVo = studentExamMapper.selectByStudentExamId(studentExamId);

//        if (paperVo.getAnswerTime() == null) {
//            Long answerTime = (paperVo.getExamEndTime().getTime() - paperVo.getExamStartTime().getTime())/60000;
//
//            paperVo.setAnswerTime(answerTime.intValue());
//        }

        List<StudentExamAreaVo> areas = examPaperAreaMapper.selectByStudentExamId(studentExamId);

        //其他题
        List<StudentExamQuestionVo> questions = studentExamQuestionMapper.selectQuestionVoByStudentExamIdNo(studentExamId);


        //填空题处理 答案个数
        if (questions != null && questions.size() > 0) {

            for (StudentExamQuestionVo seq : questions) {

                if (seq.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())) {
                    Question qt = questionMapper.selectByPrimaryKey(seq.getQuestionId());
                    if (qt != null) {
                        char[] ch = qt.getQuestionAnswer().toCharArray();
                        for (int i = 0; i < ch.length; i++) {
                            if (ch[i] == '、') {
                                // 判断是否为、
                                seq.setAnswerCount(seq.getAnswerCount() + 1);
                            }
                        }
                    }

                } else if (seq.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())) {

                    List<Integer> submitAnswer = JSON.parseArray(seq.getAnswer(), Integer.class);
                    if (submitAnswer != null && submitAnswer.size() > 0) {
                        seq.setMultipleList(submitAnswer);
                    }

                }
            }

        }

        //材料题子题母题集合
        List<StudentExamQuestionVo> materialQuestionList = studentExamQuestionMapper.selectQuestionVoByStudentExamIdB(studentExamId);

        if (materialQuestionList != null && materialQuestionList.size() > 0) {
            for (StudentExamQuestionVo sev : materialQuestionList) {

                List<StudentExamQuestionVo> questionsSon = studentExamQuestionMapper.selectQuestionVoByStudentExamIdCNo(studentExamId, sev.getMaterialQuestionId());

                for (StudentExamQuestionVo seq : questionsSon) {
                    if (seq.getQuestionType().equals(QuestionTypeEnum.GAP.getValue())) {

                        Question qt = questionMapper.selectByPrimaryKey(seq.getQuestionId());

                        if (qt != null) {
                            char[] ch = qt.getQuestionAnswer().toCharArray();
                            for (int i = 0; i < ch.length; i++) {
                                if (ch[i] == '、') {
                                    // 判断是否为、
                                    seq.setAnswerCount(seq.getAnswerCount() + 1);
                                }
                            }
                        }
                    } else if (seq.getQuestionType().equals(QuestionTypeEnum.MULTIPLE.getValue())) {

                        List<Integer> submitAnswer = JSON.parseArray(seq.getAnswer(), Integer.class);

                        if (submitAnswer != null && submitAnswer.size() > 0) {
                            seq.setMultipleList(submitAnswer);
                        }

                    }
                }

                Question que = questionMapper.selectByPrimaryKey(sev.getMaterialQuestionId());
                //子题合成母题
                StudentExamQuestionVo tv = new StudentExamQuestionVo();
                tv.setQuestionType(que.getQuestionType());
                tv.setTitle(que.getName());
                tv.setAreaId(questionsSon.get(0).getAreaId());
                tv.setSort(questionsSon.get(0).getSort());
                tv.setContent(que.getContent());
                tv.setStudentExamQuestionVo(questionsSon);
                tv.setId(que.getId());
                questions.add(tv);
            }

        }

        if (questions != null && questions.size() > 0) {
            paperVo.setQuestionCount(questions.size());
            for (StudentExamAreaVo area : areas) {
                area.setQuestions(questions.stream().filter(e -> e.getAreaId().equals(area.getAreaId())).collect(Collectors.toList()));
            }
        }
        paperVo.setAreas(areas);
        return paperVo;
    }
}
